package com.lionel.singleton;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author 714936489@qq.com
 * @date 2018/5/16 21:37
 * 懒汉式线程不安全
 */
@Slf4j
public class SingletonExample1 {
    private static AtomicInteger count = new AtomicInteger(0);
    public SingletonExample1() {
        log.info("Singleton 私有的构造方法被实例化{}次：",count.incrementAndGet());

    }
    private static SingletonExample1 instance= null;
    public static SingletonExample1 getInstance(){
        if(instance==null){
            instance = new SingletonExample1();
        }
        return instance;
    }

    public static void main1(String[] args) {
        SingletonExample1 instance1 = SingletonExample1.getInstance();
        SingletonExample1 instance2 = SingletonExample1.getInstance();
        //一个线程打印出true
        System.out.println(instance1==instance2);
    }
}
@Slf4j
class SingletonExampleTester{
    public static void main(String[] args) {
        ExecutorService threadPool = Executors.newFixedThreadPool(20);
        for (int i = 0; i< 20; i++) {
            threadPool.execute(new Runnable() {
                @Override
                public void run() {
                    log.warn("threadName:{},instance:{}",Thread.currentThread().getName(),SingletonExample1.getInstance());
                }
            });
        }
        threadPool.shutdown();
    }
}
